//
//  CYPopupAdvertisementManager.m
//  cyjf
//
//  Created by tauCross on 2017/8/30.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYPopupAdvertisementManager.h"



#define PopupAdvertisement_Path @"popup_advertisement"
#define PopupShowHistory_Path @"popup_show_history"



@implementation CYPopupAdvertisementObject

MJExtensionCodingImplementation

@end



@interface CYPopupAdvertisementManager ()

@property(nonatomic, strong)NSMutableDictionary *showHistory;

@end


@implementation CYPopupAdvertisementManager

+ (instancetype)standardManager
{
    static CYPopupAdvertisementManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[CYPopupAdvertisementManager alloc] init];
    });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if(self)
    {
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:PopupShowHistory_Path];
        NSDictionary *showHistory = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        if(showHistory == nil)
        {
            showHistory = [NSDictionary dictionary];
        }
        self.showHistory = [showHistory mutableCopy];
    }
    return self;
}

- (void)fetchLocalObjectWithResult:(void(^)(CYPopupAdvertisementObject *object))result
{
    [CYStandardDataAPI advertisement_getListWithPosition:CYDataAPIAdvertisementPositionPopup page_no:nil complete:^(CYResponse *response) {
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
            CYDataAPIAdvertisementModel *model = nil;
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:PopupAdvertisement_Path];
            if(response.code == 0)
            {
                if([response.content isKindOfClass:[NSArray class]] && [response.content count])
                {
                    model = [CYDataAPIAdvertisementModel mj_objectWithKeyValues:[response.content firstObject]];
                }
                else
                {
                    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if(result)
                        {
                            result(nil);
                        }
                    });
                    return;
                }
            }
            CYPopupAdvertisementObject *object = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
            if(object == nil || (model && ![object.model.id isEqual:model.id]))
            {
                object = [[CYPopupAdvertisementObject alloc] init];
                object.model = model;
                object.image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:model.image.tc_url]];
                if(object.image)
                {
                    [NSKeyedArchiver archiveRootObject:object toFile:path];
                }
                else
                {
                    object = nil;
                    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
                }
            }
            if(object)
            {
                NSString *nowDateString = [[NSDate date] cy_stringWithFormat:@"yyyyMMdd"];
                NSNumber *adID = object.model.id;
                NSDictionary *dict = self.showHistory[adID];
                if([dict isKindOfClass:[NSDictionary class]])
                {
                    switch(object.model.frequence.integerValue)
                    {
                        case 0:
                        {
                            NSNumber *currentCount = dict[@"count"];
                            NSNumber *maxCount = object.model.popupMaxTimes;
                            if(maxCount.integerValue != 0 && currentCount.integerValue >= maxCount.integerValue)
                            {
                                object = nil;
                            }
                            break;
                        }
                        case 1:
                        {
                            if([dict[@"date"] isEqualToString:nowDateString])
                            {
                                object = nil;
                            }
                            break;
                        }
                        case 2:
                        {
                            NSDate *lastDate = [dict[@"date"] cy_dateWithFormat:@"yyyyMMdd"];
                            NSDate *nowDate = [nowDateString cy_dateWithFormat:@"yyyyMMdd"];
                            if([nowDate timeIntervalSinceDate:lastDate] < 7 * 24 * 60 * 60)
                            {
                                object = nil;
                            }
                            break;
                        }
                        case 3:
                        {
                            NSDate *lastDate = [dict[@"date"] cy_dateWithFormat:@"yyyyMMdd"];
                            NSDate *nowDate = [nowDateString cy_dateWithFormat:@"yyyyMMdd"];
                            if([nowDate timeIntervalSinceDate:lastDate] < 30 * 24 * 60 * 60)
                            {
                                object = nil;
                            }
                            break;
                        }
                        case 4:
                        {
                            object = nil;
                            break;
                        }
                        default:
                            break;
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                if(result)
                {
                    result(object);
                }
            });
        });
    }];
}

- (void)adShowedWithadID:(NSNumber *)adID
{
    if([adID isKindOfClass:[NSNumber class]])
    {
        NSDictionary *dateDict = self.showHistory[adID];
        if(dateDict == nil)
        {
            dateDict = [NSDictionary dictionary];
        }
        NSMutableDictionary *dateDictM = [dateDict mutableCopy];
        NSString *dateString = [[NSDate date] cy_stringWithFormat:@"yyyyMMdd"];
        if(![[dateDictM objectForKey:@"date"] isEqual:dateString])
        {
            [dateDictM removeAllObjects];
            [dateDictM setObject:dateString forKey:@"date"];
            [dateDictM setObject:@0 forKey:@"count"];
        }
        [dateDictM setObject:@([dateDictM[@"count"] integerValue] + 1) forKey:@"count"];
        self.showHistory[adID] = dateDictM;
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:PopupShowHistory_Path];
            [NSKeyedArchiver archiveRootObject:self.showHistory toFile:path];
        });
    }
}

@end
